import { Model, DataTypes, Optional, Sequelize } from 'sequelize';

// 权限属性接口
interface PermissionAttributes {
  id: string;
  name: string;
  code: string;
  description: string;
  category: string;
  created_at: Date;
  updated_at: Date;
  deleted_at?: Date;
}

// 创建时可选的属性
interface PermissionCreationAttributes extends Optional<PermissionAttributes, 'id' | 'created_at' | 'updated_at'> {}

/**
 * 权限模型
 * @description 系统权限模型，用于RBAC权限控制
 */
class Permission extends Model<PermissionAttributes, PermissionCreationAttributes> implements PermissionAttributes {
  public id!: string;
  public name!: string;
  public code!: string;
  public description!: string;
  public category!: string;
  public created_at!: Date;
  public updated_at!: Date;
  public deleted_at?: Date;

  // 用于TypeScript的类型声明，表示关联关系
  public readonly roles?: any[];

  // 静态初始化方法
  public static initialize(sequelize: Sequelize): void {
    Permission.init(
      {
        id: {
          type: DataTypes.UUID,
          defaultValue: DataTypes.UUIDV4,
          primaryKey: true,
        },
        name: {
          type: DataTypes.STRING(50),
          allowNull: false,
          comment: '权限名称',
        },
        code: {
          type: DataTypes.STRING(100),
          allowNull: false,
          unique: true,
          comment: '权限编码，唯一标识',
        },
        description: {
          type: DataTypes.STRING(200),
          allowNull: true,
          comment: '权限描述',
        },
        category: {
          type: DataTypes.STRING(50),
          allowNull: false,
          comment: '权限分类，如system,article,user等',
        },
        created_at: {
          type: DataTypes.DATE,
          allowNull: false,
          defaultValue: DataTypes.NOW,
        },
        updated_at: {
          type: DataTypes.DATE,
          allowNull: false,
          defaultValue: DataTypes.NOW,
        },
        deleted_at: {
          type: DataTypes.DATE,
          allowNull: true,
        },
      },
      {
        sequelize,
        tableName: 'permissions',
        timestamps: true,
        createdAt: 'created_at',
        updatedAt: 'updated_at',
        deletedAt: 'deleted_at',
        paranoid: true, // 启用软删除
        indexes: [
          {
            name: 'permissions_code_index',
            unique: true,
            fields: ['code'],
          },
          {
            name: 'permissions_category_index',
            fields: ['category'],
          },
        ],
      }
    );
  }

  // 定义关联关系
  public static associate(models: any): void {
    // 权限与角色多对多关系
    Permission.belongsToMany(models.Role, {
      through: 'role_permissions',
      foreignKey: 'permission_id',
      otherKey: 'role_id',
      as: 'roles',
    });
  }

  /**
   * 创建系统默认权限
   */
  public static async createDefaultPermissions(): Promise<void> {
    const defaultPermissions = [
      // 系统权限
      {
        name: '系统管理',
        code: 'system:admin',
        description: '系统管理权限',
        category: 'system',
      },
      {
        name: '用户管理',
        code: 'system:user',
        description: '用户管理权限',
        category: 'system',
      },
      {
        name: '角色管理',
        code: 'system:role',
        description: '角色管理权限',
        category: 'system',
      },
      {
        name: '权限管理',
        code: 'system:permission',
        description: '权限管理权限',
        category: 'system',
      },
      
      // 文章权限
      {
        name: '文章管理',
        code: 'article:admin',
        description: '文章管理权限',
        category: 'article',
      },
      {
        name: '文章创建',
        code: 'article:create',
        description: '创建文章权限',
        category: 'article',
      },
      {
        name: '文章编辑',
        code: 'article:edit',
        description: '编辑文章权限',
        category: 'article',
      },
      {
        name: '文章删除',
        code: 'article:delete',
        description: '删除文章权限',
        category: 'article',
      },
      {
        name: '文章查看',
        code: 'article:view',
        description: '查看文章权限',
        category: 'article',
      },
      
      // 分类权限
      {
        name: '分类管理',
        code: 'category:admin',
        description: '分类管理权限',
        category: 'category',
      },
      {
        name: '分类创建',
        code: 'category:create',
        description: '创建分类权限',
        category: 'category',
      },
      {
        name: '分类编辑',
        code: 'category:edit',
        description: '编辑分类权限',
        category: 'category',
      },
      {
        name: '分类删除',
        code: 'category:delete',
        description: '删除分类权限',
        category: 'category',
      },
      
      // 标签权限
      {
        name: '标签管理',
        code: 'tag:admin',
        description: '标签管理权限',
        category: 'tag',
      },
      {
        name: '标签创建',
        code: 'tag:create',
        description: '创建标签权限',
        category: 'tag',
      },
      {
        name: '标签编辑',
        code: 'tag:edit',
        description: '编辑标签权限',
        category: 'tag',
      },
      {
        name: '标签删除',
        code: 'tag:delete',
        description: '删除标签权限',
        category: 'tag',
      },
      
      // 评论权限
      {
        name: '评论管理',
        code: 'comment:admin',
        description: '评论管理权限',
        category: 'comment',
      },
      {
        name: '评论审核',
        code: 'comment:review',
        description: '审核评论权限',
        category: 'comment',
      },
      {
        name: '评论删除',
        code: 'comment:delete',
        description: '删除评论权限',
        category: 'comment',
      },
      {
        name: '评论回复',
        code: 'comment:reply',
        description: '回复评论权限',
        category: 'comment',
      },
    ];

    // 使用事务保证数据一致性
    const transaction = await Permission.sequelize!.transaction();

    try {
      for (const permission of defaultPermissions) {
        await Permission.findOrCreate({
          where: { code: permission.code },
          defaults: permission,
          transaction,
        });
      }

      await transaction.commit();
    } catch (error) {
      await transaction.rollback();
      throw error;
    }
  }
}

export default Permission;
